#include <iostream>
#include <string>
#include <ctime>
#include <memory>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"
#include "InetAddr.hpp"

using namespace std;
using namespace yss;
using namespace protocol_ns;

void Usage(string proc)
{
    cout << "Usage: " << proc << " + ip + port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    InetAddr serveraddr(serverip, serverport);
    Factory fac;
    
    unique_ptr<Socket> cli = make_unique<TcpSocket>();
    bool res = cli->BuildClientSocket(serveraddr);
    string inbuffer;
    while(res)
    {
        sleep(1);
        // 1、构建一个请求
        auto req = fac.BuildRequest();

        // 2、对请求进行序列化
        string send_str;
        req->Serialize(&send_str);

        cout << "Serialize: \n" << send_str << endl;

        // 3、添加长度报头
        send_str = Encode(send_str);
        cout << "Encode: \n" << send_str << endl;

        // 4、"len"\r\n{ }"\r\n
        cli->Send(send_str);

        // 5、读取应答
        int n = cli->Recv(&inbuffer);
        if(n <= 0)
        {
            break;
        }
        string package = Decode(inbuffer);
        if(package.empty()) continue;

        // 6、package一定是完整的应答
        auto resp = fac.BuildResponse();

        // 6.1、反序列化
        resp->Deserialize(package);

        // 7、拿到了结构体的应答
        cout << resp->_result << "[" << resp->_code << "]" << endl;
    }
}